from machine import UART, Pin
from utils import device, format, platform
from lib.config.index import sensor_config
import time
import json

uart_AT = None
at_config = sensor_config.get_sensor("esp8266")
rx = at_config["rx"]
tx = at_config["tx"]

device_id = device.get_device_id()
device_platform = device.get_platform()
user_agent = f"id/{device_id} platform/{device_platform}"


def uart_init():
    global uart_AT
    if uart_AT:
        print("AT UART has been inited")
        return

    # rp2350必须是0,RP2040可以为1
    if platform.is_raspberry_pico():
        uart_AT = UART(
            1,  
            baudrate=115200,
            tx=Pin(tx),
            rx=Pin(rx)
        )

    if platform.is_raspberry_pico2():
        uart_AT = UART(
            0,
            baudrate=115200,
            tx=Pin(tx),
            rx=Pin(rx)
        )


def uart_write(msg):
    global uart_AT
    if not uart_AT:
        return
    uart_AT.write(msg)


def uart_wait(wait=0):
    global uart_AT
    start = time.ticks_ms()
    msg = ""
    while True:
        if uart_AT.any():
            line = uart_AT.read()
            msg = msg + str(line)
        now = time.ticks_ms()
        diff = now - start
        if diff > wait:
            start = now
            break
    # print(msg)
    # with open("/at.txt", "a+") as f:
    #     f.write(msg)
    #     f.write("\n\n")
    return msg


def connect_WIFI(ssid, password):
    uart_init()
    print("send AT cmd...")
    uart_write("AT+RESTORE\r\n")
    uart_wait(2000)
    # uart_write("AT+RST\r\n")
    # uart_wait(600)
    uart_write("AT+CWMODE=1\r\n")
    uart_wait(100)
    uart_write("AT+CIPDINFO=0\r\n")
    uart_wait(100)
    uart_write(f'AT+CWJAP="{ssid}","{password}"\r\n')
    uart_wait(8000)
    uart_write(f"AT+CIPSTA?\r\n")
    uart_wait(500)


def scan_WIFI():
    uart_write("AT+CWLAPOPT=1,31\r\n")
    uart_wait(500)
    uart_write("AT+CWLAP\r\n")
    res = uart_wait(3000)
    print(res)


def connectServer(domain, port=80):
    # uart1.write('AT+CIPDOMAIN="' + domain + '"\r\n')
    # uart_wait(1200)
    cmd = 'AT+CIPSTART="TCP","' + domain + f'",{port}\r\n'
    # print(cmd)
    uart_write(cmd)
    uart_wait(3000)


def readTCPResponse(wait):
    start = time.ticks_ms()
    msg = ""
    received_data = bytearray()
    while True:
        if uart_AT.any():
            line = uart_AT.read()
            received_data.extend(line)
            msg = msg + str(line)
        now = time.ticks_ms()
        diff = now - start
        if diff > wait:
            start = now
            break
    #print(received_data)
    if "busy" in received_data:
        raise Exception("at_busy")
    if "ERROR" in received_data:
        raise Exception("at_error")
    return format.transformResponse(received_data)


def at_send_request(cmd, wait):
    uart_write(f"AT+CIPSEND={len(cmd)}\r\n")
    uart_wait(100)
    payload = cmd
    uart_write(payload)
    return readTCPResponse(wait)


def HTTP_GET(request_url, params, type="raw"):
    """AT TCP GET请求"""
    parsed = format.format_url(request_url)
    domain = parsed["domain"]
    port = parsed["port"]
    path = parsed["path"]
    connectServer(domain, port)
    cmd = f"GET /{path} HTTP/1.1\r\nHost: {domain}\r\nUser-Agent: {user_agent}\r\n\r\n"  # Connection: close\r\n\r\n
    return at_send_request(cmd, 2000)


def HTTP_POST(request_url, payload, type="raw"):
    """AT TCP POST"""
    parsed = format.format_url(request_url)
    domain = parsed["domain"]
    port = parsed["port"]
    path = parsed["path"]
    connectServer(domain, port)
    body = json.dumps(payload)
    length = len(body.encode("utf-8"))
    cmd = (
        f"POST /{path} HTTP/1.1\r\nHost: "
        + domain
        + f"\r\nUser-Agent: {user_agent}\r\n"
        + "Content-Type: application/json\r\n"
        + f"Content-Length: {length}\r\n\r\n"
        + f"{body}"
    )
    return at_send_request(cmd, 2000)


if __name__ == "__main__":
    scan_WIFI()
    #connect_WIFI("Codemao-Office", "2<3]OzU(!h")
    connect_WIFI("iKuai2G-cc7b", "314314314")
